#include <semaphore.h>
#include <stdio.h>
#include <pthread.h>

#define M 10

sem_t sdata, srcount;
int readcount = 0; 

void * writer(void *p){
    sem_wait(&sdata);
    printf("Writing dataset\n");
    sem_post(&sdata);
    return NULL;
}

void * reader(void *p){
    sem_wait(&srcount);
    readcount = readcount +1;
    if (1==readcount)
         sem_wait(&sdata);    
    sem_post(&srcount);
    printf("Reading dataset\n");
    sem_wait(&srcount);
    readcount = readcount - 1;
    if (0==readcount)
         sem_post(&sdata);    
    sem_post(&srcount);
    return NULL;
}

int main(void)
{
    sem_init(&sdata, 0, 1); 
    sem_init(&srcount, 0, 1);    
    pthread_t tid[M], tid2[M];
    for(int i=0; i<M; i++) 
        pthread_create(&tid[i], NULL, writer, NULL);
    for(int i=0; i<M; i++) 
        pthread_create(&tid2[i], NULL, reader, NULL);
    sem_destroy(&sdata); 
    pthread_join(tid[M-1], NULL);
}